"use strict";
var q = require('q');
var models = require('./../models');
var co = require('co');
var moment = require('moment');
var EventEmitter = require('events').EventEmitter;
var Angle = require('../serialbootstrap/index').Angle;
var path = require('path');
var fs = require('fs');
var chalk = require('chalk');

/** 
 * 测距仪的帮助类
 */
class AngleHelper extends Angle.AngleController {
    /** 
     * @param {object} option 初始化参数,包括com,device:DistDeviceConfig
     */
    constructor(option) {
        super(option.com);
        /** 配置参数 */
        this.option = option;
        /** 
         * 是否可以测量
         */
        this.enabled = true;
        this.deviceList = this.option.devices.map(function (device) {
            return Object.assign(device.dataValues, {
                id: device.deviceId,
                configId: device.id
            });
        });
    }
    
    /** 
     * 循环测量,不叫停永远不停
     */
    _survey() {
        var _this = this;
        return co(function* () {
            if (!_this.enabled) {
                console.log(chalk.green('倾角计测量已经停止'));
                yield _this.closePort();
                return;
            }
            yield q.delay(1000);
            var results = yield _this.survey();
            results = results.filter(function (item) {
                return (item.x !== null) || (item.y != null);
            }).map(function (item) {
                return {
                    configId: item.configId,
                    deviceId: item.deviceId,
                    x: item.x,
                    y: item.y,
                    t: item.t,
                    date: item.time
                };
            });
            //测量到结果了
            if (results.length > 0) {
                yield models.AngleDeviceResult.bulkCreate(results);
                yield q.delay(1000); //间隔1秒后再测
            }
            //计算工具头的旋转
            var device = _this.deviceList.find(d=> { return d.section === 'ph'; });//找到工具头的倾角计
            if (device) {
                var originValue = yield models.AngleDeviceResult.findOne({
                    where: {
                        configId: device.configId
                    },
                    order: [['Date', 'ASC']]
                });
                var angleNow = results.find(t=> { return t.configId === device.configId; });
                if (angleNow) {//如果测量到了工具头(ph)的数据
                    var angle = {
                        x: device.originX + angleNow.x - originValue.x,
                        y: device.originY + angleNow.y - originValue.y
                    };
                    fs.appendFile(path.join(__dirname, './../ph_rotation.txt'), `${moment(angleNow.date).format("YYYY-MM-DD HH:mm:ss") },${angle.x},${angle.y}\r\n`);
                }
            }
            yield q.delay(1000 * 8);
            yield _this._survey();
        }).catch(function (err) {
            console.log(err.stack);
        });
    }
    
    /** 
     * 开始观测,并把数据存入数据库
     */
    startSurvey() {
        try {
            if (this.isWorking) return;
            this.emit('anglesurveystart');
            this.enabled = true;
            this.openPort();
            this._survey();
        } catch (error) {
            console.log(error);
        }
    }
    
    /** 
     * 设置为不可观测状态,一般为换顶管时
     */
    stopSurvey() {
        this.enabled = false;
        this.closePort();
        this.emit('anglesurveystop');
    }
}
module.exports = AngleHelper;